package com.cloudcc.mobile.view.activity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.MenuToggleEvent;
import com.cloudcc.cloudframe.bus.StartWebEvent;
import com.cloudcc.cloudframe.util.DensityUtils;
import com.cloudcc.cloudframe.util.SharePreferece;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.db.ApprovalDB;
import com.cloudcc.mobile.db.EventDB;
import com.cloudcc.mobile.db.TaskDB;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.util.DialogUtils;
import com.cloudcc.mobile.util.DialogUtils.OnDoClickListener;
import com.cloudcc.mobile.util.NetWork;
import com.cloudcc.mobile.util.NotificationUtils;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.cloudcc.mobile.view.web.WebViewActivtiy;
import com.cloudcc.mobile.weight.CustomProgressDialog;
import com.cloudcc.mobile.weight.ui.PullToRefreshBase;
import com.cloudcc.mobile.weight.ui.PullToRefreshBase.OnRefreshListener;
import com.cloudcc.mobile.weight.ui.PullToRefreshWebView;
import com.lidroid.xutils.exception.DbException;
/**
 * 加载的webview
 *
 */
public class WebViewActivity extends BaseActivity{
	public static final String ARG_PLANET_NUMBER = "planet_number";
	public WebView weixin;
	private ImageView fanhui;
	private ImageView shuaxin;
	private RelativeLayout caozuo;
	private CustomProgressDialog progressDialog;
	private NetWork net;
	private String urlString;
	private SharePreferece share;
	private ValueCallback<Uri> mUploadMessage;
	private final int OPEN_RESULT=1;
	private final int PINK_RESULT=2;
	private String filePath;
	private Uri uri;
	private TaskDB db3;
	private ApprovalDB db4;
	private LinearLayout network;
	private ImageView menu;
	private EventDB db5;
	private float dx;
	private float ux;
	private boolean isComeFirst;
	private PullToRefreshWebView weixinview;
	protected String mUrl = StringUtils.EMPTY;
	
	@Override
	public void init(Bundle savedInstanceState) {
		super.init(savedInstanceState);
		try {
			setView();
			addListener();
		} catch (Exception e) {
			Tools.handle(e);
		}
	}
	
	@Override
	public int getLayoutId() {
		return R.layout.webview2;
	}

	/**
	 * 滑动返回
	 */
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		//当按下时处理  
		if (ev.getAction() == MotionEvent.ACTION_DOWN) {  
			dx=ev.getX();
		}else if (ev.getAction() == MotionEvent.ACTION_UP) {// 松开处理  
			ux=ev.getX();
			if((int)(ux - dx)>DensityUtils.getScreenWidth(mContext)/2&&ux>dx){
				finish();
				//设置切换动画，从右边进入，左边退出
				overridePendingTransition(R.anim.in_from_left, R.anim.out_to_right);
			}
		}
		return super.dispatchTouchEvent(ev);
	}
	private void setView() throws DbException {
		db3=new TaskDB(mContext,UserManager.getManager().getUser().userId+"chat");
		db4=new ApprovalDB(mContext,UserManager.getManager().getUser().userId+"chat");
		db5=new EventDB(mContext,UserManager.getManager().getUser().userId+"chat");
		weixinview=(PullToRefreshWebView)findViewById(R.id.weixin);
		weixin=weixinview.getRefreshableView();
		fanhui=(ImageView)findViewById(R.id.fanhui);
		shuaxin=(ImageView)findViewById(R.id.shuaxin);
		menu=(ImageView)findViewById(R.id.webview_menubtn);
		menu.setImageResource(R.drawable.ic_navigation_previous_item);
		caozuo=(RelativeLayout)findViewById(R.id.caozuo);
		network=(LinearLayout)findViewById(R.id.network_bad);
		share=new SharePreferece(mContext);
		caozuo.setVisibility(View.GONE);
		weixin.setVisibility(View.GONE);
		progressDialog = CustomProgressDialog.createDialog(mContext);  
//		progressDialog.setMessage("正在加载中..."); 
		net=new NetWork();
		String action=getIntent().getStringExtra("MyPushMessageReceiver");
		if(action!=null&&!action.trim().equals("")&&!action.trim().equals("null")){
			if(action.equals("task")){
				NotificationUtils.clearNotification(mContext, 2001);
				db3.deleteTaskAll();
				AppContext.urlString=UrlTools.weixinUrl+UrlTools.TaskUrl;
				Intent intent=new Intent(AppContext.TASK_NUM);
				sendBroadcast(intent);
			}else if(action.equals("approval")){
				NotificationUtils.clearNotification(mContext, 2002);
				db4.deleteApprovalAll();
				AppContext.urlString=UrlTools.weixinUrl+UrlTools.ApprovalUrl;	
				Intent intent=new Intent(AppContext.DAISHENPI_NUM);
				sendBroadcast(intent);
			}else if(action.equals("event")){
				NotificationUtils.clearNotification(mContext, 2003);
				db5.deleteEventAll();
				AppContext.urlString=UrlTools.weixinUrl+UrlTools.EventUrl;	
				Intent intent=new Intent(AppContext.EVENT_NUM);
				sendBroadcast(intent);
			}
		}else{
			
		}
		webview();
	}
	/**
	 * webview操作类
	 */
	@SuppressLint("SetJavaScriptEnabled")
	public void webview() {
		weixin.requestFocus();  
		weixin.loadUrl(AppContext.urlString);
		weixin.reload();
		mUrl = AppContext.urlString;
		WebSettings webstting=weixin.getSettings();
		webstting.setJavaScriptEnabled(true);
		// 设置可以访问文件
		webstting.setAllowFileAccess(true);
		webstting.setSupportZoom(true);   
		webstting.setJavaScriptCanOpenWindowsAutomatically(true);
		weixin.setWebViewClient(new WebViewClient(){
			@Override
			public void onPageStarted(WebView view, String url,
					Bitmap favicon) {
				urlString=url;
				//startProgressDialog();
				if(url.equals(UrlTools.loginurl)){
					Intent intent=new Intent(UrlTools.loginurl);
					mContext.sendBroadcast(intent);
				}
				super.onPageStarted(view, url, favicon);
			}
			@Override
			public void onPageFinished(WebView view, String url) {
				// 加载完了再调用js登录代码
				//stopProgressDialog();
				if(AppContext.isError){
					weixin.setVisibility(View.GONE);
					caozuo.setVisibility(View.GONE);
					network.setVisibility(View.VISIBLE);
					if(!AppContext.isFirst){
						AppContext.isError=false;
					}
					AppContext.isFirst=false;
				}else{
					AppContext.isFirst=true;
					weixin.setVisibility(View.VISIBLE);
					caozuo.setVisibility(View.GONE);
					network.setVisibility(View.GONE);
				}
				super.onPageFinished(view, url);
			}
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				if (UrlManager.isWapLogin(url)) {// 跳转去登录
					EventEngine.register(WebViewActivity.this);
					Intent intent = new Intent(mContext, BindActivity.class);
					startActivity(intent);
					return true;
				}
				if(url.equals(UrlTools.weixinUrl+UrlTools.wxIndexUrl)){
					WebViewActivity.this.finish();
					return true;
				}else{
					//自身加载新链接,不做外部跳转
					view.loadUrl(url);
					return true;
				}
			}
			public void onReceivedSslError(WebView view, android.webkit.SslErrorHandler handler, android.net.http.SslError error) {
				handler.proceed();  
			};
			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				AppContext.isError=true;
				super.onReceivedError(view, errorCode, description, failingUrl);
			}
		});
		weixin.setWebChromeClient(new WebChromeClient(){
			@Override
			public boolean onJsAlert(WebView view, String url,
					String message, final JsResult result) {
				return true;
			}
			@Override
			public boolean onJsConfirm(WebView view, String url,
					String message, final JsResult result) {
				DialogUtils dialogutils=new DialogUtils(mContext);
				dialogutils.showUpdateDialog(mContext, "网页提示", message);
				dialogutils.setOnDoClicktListener(new OnDoClickListener() {
					@Override
					public void confirm() {
						 result.confirm(); 
					}
					@Override
					public void cancel() {
						result.cancel();
					}
				});
				return true;
			}
			public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {  
				if (mUploadMessage != null) return;
				mUploadMessage = uploadMsg;   
				Intent i = new Intent(Intent.ACTION_GET_CONTENT);
				i.addCategory(Intent.CATEGORY_OPENABLE);
				i.setType("*/*");
				startActivityForResult( Intent.createChooser( i, "选择文件" ), PINK_RESULT);
			}

			// For Android  > 4.1.1
			public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
				openFileChooser(uploadMsg, acceptType);
			}
			// For Android < 3.0
			public void openFileChooser(ValueCallback<Uri> uploadMsg) {
				openFileChooser( uploadMsg, "" );
			}
		});
	}
	@SuppressLint("SdCardPath")
	@Override
	public void onActivityResult(int requestCode, int resultCode,Intent intent) {  
		if(requestCode==PINK_RESULT)  {  
			if (null == mUploadMessage) return;  
			Uri result = intent == null || resultCode != RESULT_OK ? null  
					: intent.getData();  
			mUploadMessage.onReceiveValue(result);  
			mUploadMessage = null;  
		}
	}  

	/**
	 * dialog开始显示
	 */
	private void startProgressDialog(){  
		if (progressDialog == null){  
			progressDialog = CustomProgressDialog.createDialog(AppContext.getInstance());  
			progressDialog.setCancelable(true);
			progressDialog.setCanceledOnTouchOutside(false);
//			progressDialog.setMessage("正在加载中...");  
		}  
		progressDialog.show();  
	}  
	/**
	 * 停止dialog
	 */
	private void stopProgressDialog(){  
		if (progressDialog != null){  
			progressDialog.dismiss();  
			progressDialog = null;  
		}  
	} 

	/**
	 * 监听   mWebView.goBack();   //后退  
           mWebView.goForward();//前进
           mWebView.reload();  //刷新
	 */
	private void addListener() {
		/**
		 * 下拉刷新webview
		 */
		weixinview.setOnRefreshListener(new OnRefreshListener<WebView>() {
			@Override
			public void onPullDownToRefresh(PullToRefreshBase<WebView> refreshView) {
				weixin.reload(); 
				weixinview.onPullDownRefreshComplete();
			}
			@Override
			public void onPullUpToRefresh(PullToRefreshBase<WebView> refreshView) {}
		});
		network.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				weixin.reload();    //刷新
				AppContext.isFirst=true;
				AppContext.isError=false;
			}
		});
		fanhui.setOnClickListener(new OnClickListener() {@Override public void onClick(View v) {
			if(urlString.equals(UrlTools.weixinUrl+UrlTools.menuurl)){
				weixin.reload();    //刷新
			}else{
				weixin.goBack();   //后退  
			}
		}});
		shuaxin.setOnClickListener(new OnClickListener() {@Override public void onClick(View v) {
			weixin.reload();    //刷新
		}});
		menu.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				WebViewActivity.this.finish();
			}
		});
	}
	/**
	 * 重新bin定的时候
	 * 
	 * @param event
	 */
	public void onEventMainThread(StartWebEvent event) {
		if (event.isError()) {
			EventEngine.post(new MenuToggleEvent(false, false));
			this.finish();
			return;
		}
		weixin.loadUrl(mUrl);
		EventEngine.uregister(this);
	}
}